package com.twotiger.and.activity.project;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Color;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import app.twotiger.p2p.R;
import app.twotiger.p2p.R.color;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.account.recharge.RechargePage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.adapter.InvesterAdapter;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.Coupon;
import com.twotiger.and.bean.Interest;
import com.twotiger.and.bean.InverstCoupon;
import com.twotiger.and.bean.Invester;
import com.twotiger.and.bean.Order;
import com.twotiger.and.bean.RechargeBank;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.URLUtil;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.ViewUtils;

/**
 * 投资-输入金额
 * @Description: TODO(这里描述这个类的作用) 
 * @Author gao
 * @Date 2015年8月12日 下午2:50:58
 */
public class InverstInputAmountPage extends BaseActivity implements OnClickListener {
    private static final int GETASSERTSUCCES = 0;
    private static final int GETASSERTFAIL = 1;
    private static final int COUNTINVERSTSUCCES = 2;
    private static final int COUNTINVERSTFAIL = 3;
    private static final int GETCUNBANKSUCCES = 4;
    private static final int GETCUNBANKFAIL = 5;
    private static final int LOOPTOCOUNTINSERT = 6;
    protected static final int GETINVERSTCPSUCCES = 7;
    protected static final int GETINVERSTCPFAIL = 8;

    private static final int REQUESTCODE_COUPON = 9;
    public static final int COUPONRESULT_CANCELED = 10; //优惠券暂不使用的标记

    private ArrayList<Invester> investers;
    private InvesterAdapter investerAdapter;
    private ImageView sub_title_left_bt;
    private TextView sub_title_center_tv;
    private TextView acount_avalibe;
    private TextView can_inverst_text;
    private EditText input_amount_edit;
    private Button all_inverst_btn;
    private TextView expect_income;
    private Button inverst_btn;
    private HashMap<String, String> parm;
    private View input_inverst_ll;
    private String caid;
    private double avlibe; //剩余可投金额
    private UserAsset userAsset;
    private Button charge_btn;
    private Interest interest;
    private Order order;
    private RechargeBank cunbanklist;
    private TextView sub_title_right_tv;
    private String amountContent; //金额输入框的内容

    private String tempNumNow;
    private double minInvestAmount; //最小投资额    为0表示无限制
    private double maxInvestAmount; //最大投资额    为0表示无限制

    private boolean canClickBtn = false;
    private boolean isShowDialog = false;

    private TextView tv_coupon, tv_benefit;
    private RelativeLayout rl_coupon;
    private ImageView iv_coupon;

    private Coupon usedCoupon;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.input_inverst_amount_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {
        sub_title_left_bt = (ImageView) view.findViewById(R.id.sub_title_left_bt);
        sub_title_center_tv = (TextView) view.findViewById(R.id.sub_title_center_tv);
        sub_title_right_tv = (TextView) view.findViewById(R.id.sub_title_right_tv);
        acount_avalibe = (TextView) view.findViewById(R.id.acount_avalibe);
        charge_btn = (Button) view.findViewById(R.id.charge_btn);
        can_inverst_text = (TextView) view.findViewById(R.id.can_inverst_text);
        input_amount_edit = (EditText) view.findViewById(R.id.input_amount_edit);
        all_inverst_btn = (Button) view.findViewById(R.id.all_inverst_btn);
        expect_income = (TextView) view.findViewById(R.id.expect_income);
        inverst_btn = (Button) view.findViewById(R.id.inverst_btn);
        input_inverst_ll = view.findViewById(R.id.input_inverst_ll);

        rl_coupon = (RelativeLayout) view.findViewById(R.id.rl_coupon);
        tv_coupon = (TextView) view.findViewById(R.id.tv_coupon);
        tv_benefit = (TextView) view.findViewById(R.id.tv_benefit);
        iv_coupon = (ImageView) view.findViewById(R.id.iv_coupon);

    }

    @Override
    public void onClick(View view) {

        if (view == null) {
            return;
        }
        switch (view.getId()) {
        case R.id.rl_coupon:
            if (!canClickBtn) { //确保投资优惠券请求完成才可点击
                return;
            }
            if (application.getInverstcouponjson() != null) { //确保优惠券选择页面不报null指针
                InverstCoupon inverstCoupon = JSON.parseObject(application.getInverstcouponjson(),
                    InverstCoupon.class);
                ArrayList<Coupon> coupon_canlist = (ArrayList<Coupon>) JSON.parseArray(
                    inverstCoupon.getKyList(), Coupon.class);
                ArrayList<Coupon> coupon_cantlist = (ArrayList<Coupon>) JSON.parseArray(
                    inverstCoupon.getBkyList(), Coupon.class);
                if (coupon_canlist.size() == 0 && coupon_cantlist.size() == 0) { //可用优惠券和不可用优惠券均为0的时候不会跳转到选择优惠券页面

                } else {
                    if (ViewUtils.isFastDoubleClick(view)) {
                        return;
                    }
                    Intent intent = new Intent();
                    intent.setClass(mContext, SelectCouponPage.class);
                    startNewActivityforresult(intent, R.anim.push_left_in, R.anim.push_left_out,
                        REQUESTCODE_COUPON);
                }
            }
            break;
        case R.id.sub_title_right_tv:
            Intent in = new Intent(mContext, WebViewPage.class);
            in.putExtra("title", "合同");
            Map<String, String> contractmap = new HashMap<String, String>();
            contractmap.put("pType", order.getpType());
            contractmap.put("token", getToken());
            in.putExtra(
                "url",
                Constants.HOST + Constants.CONTRACT + "contractDemoHtml?"
                        + URLUtil.createContractUrl(contractmap, "3.0"));
            startNewActivity(in, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.sub_title_left_bt:
            onBackPress();
            break;
        case R.id.charge_btn:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (cunbanklist != null && userAsset != null) {
                Intent intent = new Intent(mContext, RechargePage.class);
                intent.putExtra("CHARGE", userAsset.avaliable);
                intent.putExtra("RECHARGEBANK", cunbanklist);
                startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
            }
            break;
        case R.id.all_inverst_btn: //全投
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (avlibe != 0.00 && userAsset != null) {
                if (avlibe >= userAsset.avaliable) {//项目可投大于用户资金
                    input_amount_edit.setText(ArithUtils.coverMoney(userAsset.avaliable + ""));
                    input_amount_edit.setSelection(ArithUtils.coverMoney(userAsset.avaliable + "")
                        .length());
                } else {
                    input_amount_edit.setText(ArithUtils.coverMoney(avlibe + ""));//项目可投小于用户资金
                    input_amount_edit.setSelection(ArithUtils.coverMoney(avlibe + "").length());
                }
            }
            break;
        case R.id.inverst_btn:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            String amount = input_amount_edit.getText().toString().trim();
            if (StringUtils.isEmpty(amount)) {
                showToast("请输入投资金额");
                return;
            }
            if (minInvestAmount != 0) {
                if (Double.parseDouble(amount) < minInvestAmount) {
                    showToast("起投金额" + ArithUtils.coverMoney(minInvestAmount + "") + "元起");
                    return;
                }
            }
            if (maxInvestAmount != 0) {
                if (Double.parseDouble(amount) > maxInvestAmount) {
                    showToast("最大投资额度为：" + ArithUtils.coverMoney(maxInvestAmount + ""));
                    return;
                }
            }
            if (Double.parseDouble(amount) > avlibe) {
                showToast("剩余可投金额为：" + ArithUtils.coverMoney(avlibe + ""));
                return;
            }
            if (userAsset == null) { //保证用户资产请求完成才可以点击按钮进行下一步
                return;
            }
            order.setCanuse(userAsset.avaliable);
            if ("预期收益：计算中...".equals(expect_income.getText().toString().trim())) { //如果显示正在计算中，不能到下一步。因为下一个页面要用到预计收益         interest == null
                return;
            }
            order.setExpectinterest(interest.getInterest());
            order.setInverstamount(Double.valueOf(amount));

            if (application.getInverstcouponjson() != null) { //确保优惠券选择页面不报null指针
                InverstCoupon inverstCoupon = JSON.parseObject(application.getInverstcouponjson(),
                    InverstCoupon.class);
                final ArrayList<Coupon> coupon_canlist = (ArrayList<Coupon>) JSON.parseArray(
                    inverstCoupon.getKyList(), Coupon.class);
                ArrayList<Coupon> coupon_cantlist = (ArrayList<Coupon>) JSON.parseArray(
                    inverstCoupon.getBkyList(), Coupon.class);
                if (coupon_canlist.size() != 0 && !isShowDialog) { //可用优惠券不为0
                    PromptManager.showCouponAlertHasBtn(InverstInputAmountPage.this, "优惠券使用提醒",
                        "您有" + coupon_canlist.size() + "张优惠券可用，可产生额外收益或抵用现金", "暂不使用优惠券", "去选择",
                        new ReChargeClickListener() {

                            @Override
                            public void onClickConfirm() {
                                isShowDialog = true;
                                Intent intent = new Intent(mContext, InverstConfirmPage.class)
                                    .putExtra("ORDER", order).putExtra("COUPON", usedCoupon)
                                    .putExtra("NUMBER", coupon_canlist.size());
                                startNewActivityforresult(intent, R.anim.push_left_in,
                                    R.anim.push_left_out, ProjectDetailPage.TENDERREQUEST);
                            }

                            @Override
                            public void onClickCancel() {
                                Intent intent = new Intent();
                                intent.setClass(mContext, SelectCouponPage.class);
                                startNewActivityforresult(intent, R.anim.push_left_in,
                                    R.anim.push_left_out, REQUESTCODE_COUPON);
                            }
                        });
                } else {
                    Intent intent = new Intent(mContext, InverstConfirmPage.class)
                        .putExtra("ORDER", order).putExtra("COUPON", usedCoupon)
                        .putExtra("NUMBER", coupon_canlist.size());
                    startNewActivityforresult(intent, R.anim.push_left_in, R.anim.push_left_out,
                        ProjectDetailPage.TENDERREQUEST);
                }
            }
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent intent) {
        super.onActivityResult(requestcode, resultcode, intent);
        if (requestcode == ProjectDetailPage.TENDERREQUEST) {
            if (resultcode == ProjectDetailPage.TENDERRESULTCLOSE_SUC) {
                setResult(ProjectDetailPage.TENDERRESULTCLOSE_SUC);
                finish();
            } else if (resultcode == ProjectDetailPage.TENDERRESULTCLOSE_FAI) {
                setResult(ProjectDetailPage.TENDERRESULTCLOSE_FAI);
                finish();
            }
        }
        if (requestcode == REQUESTCODE_COUPON && resultcode == RESULT_OK) {
            Coupon coupon = (Coupon) intent.getSerializableExtra("COUPON");
            usedCoupon = coupon;
            isShowDialog = true;
            switch (coupon.getAwardType()) {
            case 4:
                //代金券
                tv_coupon.setText(usedCoupon.getAwardValue() + "元" + coupon.getAwardTypeName());
                tv_coupon.setTextColor(InverstInputAmountPage.this.getResources().getColor(
                    color.black));
                tv_coupon.setBackgroundColor(Color.TRANSPARENT);
                double couponvalue = Double.valueOf(coupon.getAwardValue());
                tv_benefit.setText("已抵用" + ArithUtils.coverMoney(couponvalue + "") + "元");
                break;
            case 1:
                //加息券
                tv_coupon.setText(usedCoupon.getAwardValue() + "%" + coupon.getAwardTypeName());
                tv_coupon.setTextColor(InverstInputAmountPage.this.getResources().getColor(
                    color.black));
                tv_coupon.setBackgroundColor(Color.TRANSPARENT);
                tv_benefit.setText("可额外产生" + ArithUtils.coverMoney(coupon.getAddInterest() + "")
                                   + "元");
                break;
            default:
                break;
            }

        } else if (requestcode == REQUESTCODE_COUPON && resultcode == COUPONRESULT_CANCELED) {

            isShowDialog = true;
            usedCoupon = null;
            tv_coupon.setText("暂不使用优惠券");
            tv_coupon.setTextColor(InverstInputAmountPage.this.getResources()
                .getColor(color.gray_1));
            tv_coupon.setBackgroundColor(Color.TRANSPARENT);
            tv_benefit.setText("");
        }
    }

    @Override
    protected void setListener() {

        amountContent = input_amount_edit.getText().toString().trim();

        inverst_btn.setOnClickListener(this);
        all_inverst_btn.setOnClickListener(this);
        sub_title_left_bt.setOnClickListener(this);
        sub_title_right_tv.setOnClickListener(this);
        charge_btn.setOnClickListener(this);
        rl_coupon.setOnClickListener(this);

        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETINVERSTCPSUCCES: //获取优惠券成功
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        InverstCoupon coupon = JSON.parseObject(result.data, InverstCoupon.class);
                        application.setInverstcouponjson(result.data);
                        canClickBtn = true;
                        isShowDialog = false;
                        List<Coupon> canuse_list = JSON
                            .parseArray(coupon.getKyList(), Coupon.class);
                        List<Coupon> canuse_canot_list = JSON.parseArray(coupon.getBkyList(),
                            Coupon.class);
                        if (canuse_list.size() != 0) {
                            tv_coupon.setText(canuse_list.size() + "张可用");
                            tv_coupon.setTextColor(InverstInputAmountPage.this.getResources()
                                .getColor(color.white));
                            tv_coupon.setBackgroundResource(R.drawable.corner_shape_coupon);
                            tv_benefit.setText("");
                            iv_coupon.setVisibility(View.VISIBLE);
                            rl_coupon.setEnabled(true);
                        } else {
                            tv_coupon.setText("暂无可用优惠券");
                            tv_coupon.setTextColor(InverstInputAmountPage.this.getResources()
                                .getColor(color.gray_1));
                            tv_coupon.setBackgroundColor(Color.TRANSPARENT);
                            tv_benefit.setText("");
                            iv_coupon.setVisibility(View.INVISIBLE);
                            rl_coupon.setEnabled(false);
                        }
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;
                case GETINVERSTCPFAIL:
                    showToast("网络异常");
                    break;
                case GETASSERTSUCCES:
                    Basebean result_1 = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_1.isOk()) {
                        userAsset = JSONObject.parseObject(result_1.data, UserAsset.class);
                        acount_avalibe.setText(ArithUtils.coverMoney(userAsset.avaliable + ""));
                    } else {
                        showToast(result_1.codeDesc);
                    }
                    break;
                case GETASSERTFAIL:

                    break;
                case COUNTINVERSTSUCCES:
                    Basebean result_c = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_c.isOk()) {
                        interest = JSON.parseObject(result_c.data, Interest.class);
                        expect_income
                            .setText("预期收益：" + ArithUtils.formatFloatNumber(interest.getInterest())
                                     + "元");
                    } else {
                        showToast(result_c.codeDesc);
                    }
                    break;
                case COUNTINVERSTFAIL:

                    break;

                case GETCUNBANKSUCCES:
                    Basebean result_b = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_b.isOk()) {
                        cunbanklist = JSON.parseObject(result_b.data, RechargeBank.class);

                    } else {
                        showToast(result_b.codeDesc);
                    }
                    break;
                case GETCUNBANKFAIL:

                    break;
                case LOOPTOCOUNTINSERT: //轮询看是否需要计算收益
                    tempNumNow = amountContent;
                    String temp = (String) msg.obj;
                    if (!StringUtils.isEmpty(tempNumNow) && Double.parseDouble(tempNumNow) != 0) {
                        if (tempNumNow.equals(temp)) {
                            if (!ArithUtils.isValidAmount(tempNumNow)) {
                                showToast("请输入有效金额");
                                break;
                            }
                            countinsert(tempNumNow.toString());
                            getinverstcoupon(tempNumNow.toString());
                        }
                    }
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
        input_amount_edit.addTextChangedListener(new TextWatcher() {

            String aaa = "";

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                aaa = s.toString(); //edittext变化之前的内容
            }

            @Override
            public void afterTextChanged(Editable s) {
                String bbb = s.toString();//edittext变化之后的内容
                if (".".equals(s.toString())) {
                    input_amount_edit.setText("");
                    return;
                }
                if (!bbb.equals(aaa)) {
                    if (!StringUtils.isEmpty(s.toString())) {
                        if (Double.parseDouble(s.toString()) > avlibe) {
                            showToast("输入金额不能大于剩余可投金额");
                            input_amount_edit.setText(aaa);
                            input_amount_edit.setSelection(aaa.length() - 1);
                            return;
                        }
                    }
                    if (!StringUtils.isEmpty(s.toString())) {
                        if (Double.parseDouble(s.toString()) == 0) {
                            expect_income.setText("预期收益：");
                            amountContent = s.toString();
                        } else {
                            expect_income.setText("预期收益：计算中...");
                            amountContent = s.toString();
                        }
                    } else {
                        expect_income.setText("预期收益：");
                        amountContent = s.toString();
                    }
                    String tempNumPre = amountContent;
                    Message preNumMes = Message.obtain();
                    preNumMes.obj = tempNumPre;
                    preNumMes.what = LOOPTOCOUNTINSERT;
                    handler.sendMessageDelayed(preNumMes, 1000); //发送一个延迟3秒的消息。系统收到消息后会对比文本框内容是否有变化。如果没有变化则请求预期收益接口

                    canClickBtn = false;

                    if (!StringUtils.isEmpty(s.toString())) {
                        if (Double.parseDouble(s.toString()) < 100) {
                            input_amount_edit.setTextColor(InverstInputAmountPage.this
                                .getResources().getColor(color.gray));
                        } else {
                            input_amount_edit.setTextColor(InverstInputAmountPage.this
                                .getResources().getColor(color.gray));
                        }
                    }
                }
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 获取投资优惠券
     * @param amount 
     */
    private void getinverstcoupon(String amount) {
        canClickBtn = false;
        parm.clear();
        parm.put("token", getToken());
        parm.put("projectId", order.getProjectid());
        parm.put("amount", ArithUtils.coverMoney(amount));
        getDate(parm, Constants.INVESTACTQUERY, handler, GETINVERSTCPSUCCES, GETINVERSTCPFAIL,
            false, true, false);
    }

    @Override
    protected void processLogic() {
        input_amount_edit.requestFocus();
        parm = getParm();
        //弹出键盘
        this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        initPage();
        getchargebankcards();
        investers = new ArrayList<Invester>();
        investerAdapter = new InvesterAdapter(InverstInputAmountPage.this, investers);
    }

    private void initPage() {
        order = (Order) getIntent().getSerializableExtra("ORDER");
        if(order == null){
            return;
        }
        minInvestAmount = order.getMinInvest();
        maxInvestAmount = order.getMaxInvest();
        if (minInvestAmount == 0) {
            input_amount_edit.setHint("请输入投资金额(无限额)");
        } else {
            input_amount_edit.setHint("请输入投资金额(" + ArithUtils.coverMoney(minInvestAmount + "")
                                      + "元起)");
        }
        avlibe = order.getCaninverst();
        sub_title_left_bt.setVisibility(View.VISIBLE);
        sub_title_left_bt.setImageDrawable(this.getResources().getDrawable(R.drawable.leftback));
        //根据ContractDemoMethod字段的返回是否为空，来判断协议是否显示
        if (StringUtils.isEmpty(order.getpType())) {
            sub_title_right_tv.setVisibility(View.GONE);
        } else {
            sub_title_right_tv.setVisibility(View.VISIBLE);
        }
        sub_title_right_tv.setText("协议");
        sub_title_center_tv.setText("投资金额");
        can_inverst_text.setText("剩余可投资额度：" + ArithUtils.coverMoney(avlibe + "") + "元");
        getuserassert();
    }

    private void getuserassert() {
        parm.clear();
        parm.put("token", getToken());
        getDate(parm, Constants.ASSETQUERY, handler, GETASSERTSUCCES, GETASSERTFAIL, false, true,
            false);
    }

    private void countinsert(String money) {
        parm.clear();
        parm.put("token", getToken());
        parm.put("projectId", order.getProjectid());
        parm.put("amount", ArithUtils.coverMoney(money));
        if (caid != null) {
            parm.put("caid", caid);
        }
        parm.put("mode", order.getMode());
        parm.put("type", order.getType());
        getDate(parm, Constants.CALINTEREST, handler, COUNTINVERSTSUCCES, COUNTINVERSTFAIL, false,
            true, false);
    }

    private void getchargebankcards() {
        parm.clear();
        parm.put("token", getToken());
        getDate(parm, Constants.RECHARGEBANKQUERY, handler, GETCUNBANKSUCCES, GETCUNBANKFAIL, true,
            true, false);
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.silent_anim, R.anim.slide_out_to_bottom);
    }

}
